package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"time"
)

func Middleware() gin.HandlerFunc{
	return func(c *gin.Context) {
		t := time.Now()
		fmt.Println("中间件开始执行")
		c.Set("request","中间件")

		// 执行函数
		c.Next()
		status := c.Writer.Status()
		fmt.Println("中间件执行完毕", status)
		t2:=  time.Since(t)
		fmt.Println("time:", t2)
	}
}


//--------------------------------全局中间件
//func main() {
//	r:= gin.Default()
//	r.Use(Middleware())
//	{
//		r.GET("/ce", func(c *gin.Context) {
//			req, _ := c.Get("request")
//			fmt.Println("request:", req)
//			// 页面接收
//			c.JSON(http.StatusOK, gin.H{"request": req})
//		})
//
//	}
//	r.Run(":8523")
//
//}

//----------------------------------局部中间件
//func main() {
//	r:= gin.Default()
//	r.GET("/ce",Middleware(), func(c *gin.Context) {
//		req,_:= c.Get("request")
//		fmt.Println("request:", req)
//		// 页面接收
//		c.JSON(http.StatusOK, gin.H{"request": req})
//	})
//	r.Run(":8523")
//}

func mytime(c *gin.Context)  {
	start := time.Now()
	c.Next()
	since := time.Since(start)
	fmt.Println("执行时间",since)
}

func shopIndexHandler(c *gin.Context){
	time.Sleep(5 * time.Second)
}
func shopHomeHandler(c *gin.Context) {
	time.Sleep(3 * time.Second)
}


func main() {
	r:= gin.Default()
	// 注册中间件
	r.Use(mytime)
	shoppingGroup := r.Group("shopping")
	{
		shoppingGroup.GET("/index",shopIndexHandler)
		shoppingGroup.GET("/home",shopHomeHandler)
	}
	r.Run(":8900")
}
